import Router from '@koa/router';
import response from '../response.js';
import AdmZip from 'adm-zip';
import fs from 'fs'
import fse from 'fs-extra'
import path from 'path'
import moment from 'moment';

const router = new Router();
router.prefix('/api');

//上传前端zip文件并解压到软件根目录下View文件夹
router.post('/sys/upload', async (ctx) => {
    try {
        let file = ctx.request.files.file;
        if (!file) {
            ctx.body = response.error('No file uploaded');
            return;
        }
        //检查文件扩展名是否为zip
        if (file.mimetype != 'application/zip') {
            ctx.body = response.error('File type error');
            return;
        }
        //把上传的文件保存到软件根目录下
        let reader = fs.createReadStream(file.filepath);
        let filePath = '';
        let filename = ctx.request.body.filename;
        if (filename == undefined) {
            filename = file.originalFilename;
        }
        filePath = path.join('./', filename);
        let upStream = fs.createWriteStream(filePath);
        reader.pipe(upStream);

        //等待文件写入完成
        await new Promise((resolve, reject) => {
            upStream.on('finish', resolve);
            upStream.on('error', reject);
        });

        //解压zip文件到软件根目录下View文件夹
        let zip = new AdmZip(filePath);
        zip.extractAllTo('./', true);
        //删除上传的zip文件
        fs.unlinkSync(filePath);

        //检查./dest文件夹是否存在
        const dirPath = './dist';
        const targetDir = './View';
        // 检查 dirPath 是否存在
        if (fs.existsSync(dirPath)) {
            // 检查 targetDir 是否存在，如果不存在则创建
            if (!fs.existsSync(targetDir)) {
                fs.mkdirSync(targetDir, { recursive: true });
            }
            // 获取 dirPath 下的所有文件
            const files = fs.readdirSync(dirPath);
            // 移动文件到 targetDir
            files.forEach(file => {
                const srcPath = path.join(dirPath, file);
                const destPath = path.join(targetDir, file);
                fse.moveSync(srcPath, destPath, { overwrite: true });
            });
            //删除dist文件夹
            fse.removeSync(dirPath);


            console.log('Files moved successfully.');
        } else {
            ctx.body = response.fail('解压后未发现dist文件夹');
            return;
        }

        ctx.body = response.success();
    } catch (err) {
        console.log('file upload failed', err.message);
        ctx.body = response.fail('File upload failed');
    }
}
);


router.post('/file/upload', async (ctx) => {
    try {
        let file = ctx.request.files.file;
        if (!file) {
            ctx.body = response.error('No file uploaded');
            return;
        }
        // //检查文件扩展名是否为zip
        // if (file.mimetype != 'application/zip') {
        //     ctx.body = response.error('File type error');
        //     return;
        // }
        //把上传的文件保存到软件根目录下
        let reader = fs.createReadStream(file.filepath);
        let filePath = '';
        let filename = ctx.request.body.filename;
        if (filename == undefined) {
            filename = file.originalFilename;
        }
        filePath = path.join('./View/File', filename);
        // 检查 filePath 是否存在，如果不存在则创建
        if (!fs.existsSync('./View/File')) {
            fs.mkdirSync('./View/File', { recursive: true });
        }
        let upStream = fs.createWriteStream(filePath);
        reader.pipe(upStream);

        //等待文件写入完成
        await new Promise((resolve, reject) => {
            upStream.on('finish', resolve);
            upStream.on('error', reject);
        });

        ctx.body = response.success({ filename, filePath: `/File/${filename}` });
    } catch (err) {
        console.log('file upload failed', err.message);
        ctx.body = response.fail('File upload failed');
    }
}
);



export { router };
